//
//  HNSH_AddAdminViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/7.
//

#import "HNSH_AddAdminViewController.h"
//view
#import "HNSH_AddMembersTopView.h"
#import "HNSH_CreateChatGroupCell.h"

@interface HNSH_AddAdminViewController ()

/** */
@property (nonatomic, strong)UIButton * rightBtn;
/** */
@property (nonatomic, strong)HNSH_AddMembersTopView * topView;
/** */
@property (nonatomic, copy)NSArray * titlesArray;
/** */
@property (nonatomic, strong)NSMutableDictionary * mDic;
/** */
@property (nonatomic, strong)NSMutableArray * dataArray;

@end

static NSString *HNSH_CreateChatGroupCellID = @"HNSH_CreateChatGroupCellID";

@implementation HNSH_AddAdminViewController

//MARK: Cycle Methods
- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self showNavTitle:@"添加群管理员" showLeftItem:YES];
    
    [self addAllViews];
    [self configTableView];
    
    [self setDefaultDataWithArray:self.membersArray];
}

- (void)configTableView {
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(kNavBarAndStatusBarHeight+52, 0, 84 + kBottomSafeHeight, 0));
    }];
    self.tableView.rowHeight = 64;
    [self.tableView registerClass:[HNSH_CreateChatGroupCell class] forCellReuseIdentifier:HNSH_CreateChatGroupCellID];
}

//MARK: Myself Methods
- (void)addAllViews{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.rightBtn];
    [self.tableView reloadData];
}

- (void)setDefaultDataWithArray:(NSArray *)array{
    self.mDic = [NSMutableDictionary new];
    for (HNSH_ChatFriendModel * friend in array) {
        if (friend.role == 1 || friend.role == 10 || [friend.user.uid isEqualToString:[ST_UserManager shareInstance].rcUser.uid]) {
            //管理--群主--自己自动过滤
        } else {
            NSString * name = friend.user.display_name.length ? friend.user.display_name : friend.user.name;
            if (name && name.length) {
                NSString * cityMutableString = [NSMutableString stringWithString:name];
                CFStringTransform((__bridge CFMutableStringRef)cityMutableString, NULL, kCFStringTransformMandarinLatin, NO);
                CFStringTransform((__bridge CFMutableStringRef)cityMutableString, NULL, kCFStringTransformStripCombiningMarks, NO);
                NSString * firstLetter = [[cityMutableString uppercaseString] substringToIndex:1];
                if (![NSString judgeString:firstLetter]) {
                    firstLetter = @"#";
                }
                if ([self.mDic objectForKey:firstLetter]) {
                    NSMutableArray * mCityArray = self.mDic[firstLetter];
                    if (mCityArray) {
                        [mCityArray addObject:friend];
                        self.mDic[firstLetter] = mCityArray;
                    } else {
                        self.mDic[firstLetter] = [NSMutableArray arrayWithArray:@[friend]];
                    }
                } else {
                    [self.mDic setObject:[NSMutableArray arrayWithArray:@[friend]] forKey:firstLetter];
                }
            }
        }
    }
    self.titlesArray = [self reqDiction:self.mDic];
    [self.tableView reloadData];
}

- (NSArray *)reqDiction:(NSDictionary *)dict{
    NSArray * allKeyArray = [dict allKeys];
    NSArray * afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    NSMutableArray * valueArray = [NSMutableArray array];
    for (NSString * sortsing in afterSortKeyArray) {
        NSString * valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    return afterSortKeyArray;
}

//MARK: 添加成员
- (void)rightBtnAction{
    if (!self.dataArray.count) {
        [self.view makeToast:@"请选择你要添加的管理员"];
        return;
    }
    [HNSH_ChatNetServer requestRongCloudGroupManagerAddWithGroupId:self.targetId member_ids:[self getNewMembersWithArray:self.dataArray] success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"添加成功"];
            [self.navigationController popToViewController:self.navigationController.viewControllers[self.navigationController.viewControllers.count-5] animated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 获取新增群成员列表
- (NSArray *)getNewMembersWithArray:(NSArray *)array{
    NSMutableArray * arr = [NSMutableArray new];
    for (HNSH_ChatFriendModel * model in array) {
        [arr addObject:model.user.user_id];
    }
    return arr.copy;
}

- (void)searchWithKeyword:(NSString *)keyword{
    NSArray * friArray = [NSArray arrayWithArray:self.membersArray];
    if (keyword.length) {
        NSMutableArray * array = [NSMutableArray array];
        for (HNSH_ChatFriendModel * fri in friArray) {
            if ([fri.user.name containsString:keyword] || [fri.user.display_name containsString:keyword]) {
                [array addObject:fri];
            }
        }
        [self setDefaultDataWithArray:array.copy];
    } else {
        [self setDefaultDataWithArray:self.membersArray];
    }
}

//MARK: Getter Methods
- (UIButton *)rightBtn{
    if (!_rightBtn) {
        _rightBtn = [UIButton new];
        _rightBtn.frame = CGRectMake(kScreenWidth - 88 - 16, kScreenHeight - 42 - kBottomSafeHeight, 88, 30);
        [_rightBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _rightBtn.layer.cornerRadius = 15;
        _rightBtn.layer.masksToBounds = YES;
        _rightBtn.backgroundColor = [UIColor appGreenColor];
        [_rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}

- (HNSH_AddMembersTopView *)topView{
    if (!_topView) {
        _topView = [[HNSH_AddMembersTopView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 52)];
        
        WeakSelf(weakSelf);
        _topView.searchBlock = ^(NSString * _Nonnull keyword) {
            [weakSelf searchWithKeyword:keyword];
        };
    }
    return _topView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [@[] mutableCopy];
    }
    return _dataArray;
}

//MARK: UITableViewDelegate Methods
- (UIView *)xy_noDataView{
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titlesArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString * key = self.titlesArray[section];
    NSArray * arr = self.mDic[key];
    return arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HNSH_CreateChatGroupCell * cell = [tableView dequeueReusableCellWithIdentifier:HNSH_CreateChatGroupCellID];
    NSString * key = self.titlesArray[indexPath.section];
    NSArray * arr = self.mDic[key];
    HNSH_ChatFriendModel * model = arr[indexPath.row];
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 35)];

    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kScreenWidth - 40, 35)];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:15];
    NSString * key = self.titlesArray[section];
    label.text = key;
    [view addSubview:label];

    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * key = self.titlesArray[indexPath.section];
    NSArray * arr = self.mDic[key];
    HNSH_ChatFriendModel * model = arr[indexPath.row];
    if (model.selected) {
        model.selected = NO;
        [self.dataArray removeObject:model];
    } else {
        model.selected = YES;
        [self.dataArray addObject:model];
    }
    self.topView.dataArray = self.dataArray.copy;
    [self.rightBtn setTitle:[NSString stringWithFormat:@"%@(%ld)", @"完成", self.dataArray.count] forState:UIControlStateNormal];
    [self.tableView reloadData];
}

@end
